//
//  MyShoppingCarViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/19.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyShoppingCarViewController.h"
#import "MyShoppingCarTableViewCell.h"
#import "StoneStreetStoreDetailViewController.h"
#import "SureIndentViewController.h"
static NSString * cellIndentifier = @"MyShoppingCarTableViewCell";

@interface MyShoppingCarViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *countView;
@property (weak, nonatomic) IBOutlet UIButton *deleteButton;
@property (weak, nonatomic) IBOutlet UILabel *totalPrice;
@property(nonatomic,assign)BOOL ifDelete;
@property(nonatomic,strong)NSMutableArray * goodsArray;
@property(nonatomic,strong)NSMutableDictionary * choseDic;
@property(nonatomic,assign)CGFloat totalMoney;
@end

@implementation MyShoppingCarViewController

- (void)viewWillAppear:(BOOL)animated{
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _totalMoney = 0;
    _ifDelete = NO;
    _goodsArray = [NSMutableArray array];
    _choseDic = [NSMutableDictionary dictionary];

    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.countView];
    
    [_tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;

}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getShopCarList];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.goodsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getShopCarList];
        });
    }
    
}

#pragma mark === 获取购物车列表
- (void)getShopCarList{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"page"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryCartList withHttpType:@"POST" withTag:GS_GS_queryCartList];
}



#pragma mark  === 删除
- (IBAction)deleteHandel:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _countView.hidden = YES;
        _ifDelete = YES;
        [_tableView reloadData];
    }else{
        _countView.hidden = NO;
        _ifDelete = NO;
        [_tableView reloadData];
    }
   
}

#pragma mark  === 确认删除
- (IBAction)sureDeleteHandel:(id)sender {
    if (_choseDic.allKeys.count==0) {
        [CWHUDTips showTips:@"请选择要删除的商品！"];
        return;
    }
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];

    NSString * carIds = @"";
    for (NSIndexPath * path in _choseDic.allValues) {
        NSDictionary  * dict = _goodsArray[path.section][@"mallCartDetail"][path.row];
        NSString * carId = @"";
        if (path == [_choseDic.allValues lastObject]) {
            carId = [NSString stringWithFormat:@"%@",dict[@"mallGoods"][@"mgooId"]];
        }else{
            carId = [NSString stringWithFormat:@"%@,",dict[@"mallGoods"][@"mgooId"]];
        }
        carIds = [carIds stringByAppendingString:carId];
    }
    [dic setObject:carIds forKey:@"mgooId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_deleteCartGoods withHttpType:@"POST" withTag:GS_GS_deleteCartGoods];
}

#pragma mark  === 结算
- (IBAction)payHandel:(id)sender {
    
    if (_choseDic.allKeys.count==0) {
        [CWHUDTips showTips:@"请选择商品！"];
        return;
    }
    
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"SupplyChainStoryboard" bundle:nil];
    SureIndentViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"SureIndent"];
    page.productArray = _goodsArray;
    page.choseDic = _choseDic;
    page.totalPrice = _totalMoney;
    [[Common getNavigation]pushViewController:page];

}


#pragma mark ==== 计算总价
- (void)countPrice{
    _totalMoney= 0;
    for (int i = 0; i<_choseDic.allKeys.count; i++) {
        NSIndexPath * indexP = _choseDic[_choseDic.allKeys[i]];
        NSDictionary * dic = _goodsArray[indexP.section][@"mallCartDetail"][indexP.row];
        _totalMoney +=[dic[@"mallGoods"][@"mgooPrice"] floatValue]*[dic[@"mcdeCount"]integerValue];
    }
    _totalPrice.text = [NSString stringWithFormat:@"￥%.2lf",_totalMoney];
    
}


#pragma mark === sectionHandel

- (void)choseAllSection:(UIButton *)sender{
    sender.selected = !sender.selected;
    NSArray * array = _goodsArray[sender.tag/100-1][@"mallCartDetail"];
    
    for (int i = 0; i<array.count; i++) {
        
        MyShoppingCarTableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:sender.tag/100-1]];
        
        if (sender.selected) {
            [_choseDic setObject:[NSIndexPath indexPathForRow:i inSection:sender.tag/100-1] forKey:[NSString stringWithFormat:@"%ld%d",sender.tag/100-1,i]];
            cell.choseButton.selected = YES;
        }else{
            [_choseDic removeObjectForKey:[NSString stringWithFormat:@"%ld%d",sender.tag/100-1,i]];
            cell.choseButton.selected = NO;
        }
    }
    
    [self countPrice];
}

- (void)goStore:(UIButton *)sender{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    StoneStreetStoreDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"StoneStreetStoreDetail"];
    page.storeId = _goodsArray[sender.tag/100-1][@"mstoId"];
    [[Common getNavigation]pushViewController:page];

}

#pragma mark  ==== tableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 37*VerticalRatio();
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 37), NO)];
    view.backgroundColor = [UIColor whiteColor];
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = flexibleFrame(CGRectMake(0, 0, 45, 37), NO);
    [button setImage:[UIImage imageNamed:@"shoppingCar4"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"shoppingCar5"] forState:UIControlStateSelected];
    
    button.tag = 100*(section+1)+1;
    [button addTarget:self action:@selector(choseAllSection:) forControlEvents:UIControlEventTouchUpInside];
    
    NSInteger count = 0;
    for (int i = 0; i<_choseDic.allKeys.count; i++) {
        NSString * key = _choseDic.allKeys[i];
        if ([[key substringToIndex:1] isEqualToString:[NSString stringWithFormat:@"%ld",(long)section]]) {
            count ++;
        }
    }
    NSArray * array = _goodsArray[section][@"mallCartDetail"];
    if (array.count == count) {
        button.selected = YES;
    }
    
    
    UIButton * Button = [UIButton buttonWithType:UIButtonTypeCustom];
    Button.frame = flexibleFrame(CGRectMake(37, 0, 250, 37), NO);
    NSString * name = [NSString stringWithFormat:@"%@",_goodsArray[section][@"mstoName"]];
    [Button setTitle:name forState:UIControlStateNormal];
    [Button setTitleColor:[UIColor colorWithWhite:0.200 alpha:1.000] forState:UIControlStateNormal];
    Button.titleLabel.font = [UIFont systemFontOfSize:16*VerticalTexeRatio()];
    Button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    Button.tag = 100*(section+1)+2;
    [Button addTarget:self action:@selector(goStore:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:Button];
    [view addSubview:button];
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(300, 11, 7, 13), NO)];
    imageView.image = [UIImage imageNamed:@"personal10"];
    [view addSubview:imageView];
    
    UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 36, 320, 1), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.937 alpha:1.000];
    [view addSubview:line];

    return view;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _goodsArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray * array = _goodsArray[section][@"mallCartDetail"];
    return array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_ifDelete == YES) {
        return 120*VerticalRatio();
    }else{
        return 150*VerticalRatio();
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyShoppingCarTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[MyShoppingCarTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }

    if (_ifDelete == YES) {
        cell.bottomView.hidden = YES;
        cell.totalLabel.frame = flexibleFrame(CGRectMake(198, 90, 38, 15), NO);
        cell.totalPriceLabel.frame = flexibleFrame(CGRectMake(228, 87, 90, 21), NO);
        cell.line.frame = flexibleFrame(CGRectMake(0, 115, 320 , 5), NO);
    }else{
        cell.bottomView.hidden = NO;
        cell.totalLabel.frame = flexibleFrame(CGRectMake(198, 120, 38, 15), NO);
        cell.totalPriceLabel.frame = flexibleFrame(CGRectMake(228, 117, 90, 21), NO);
        cell.line.frame = flexibleFrame(CGRectMake(0, 145, 320, 5), NO);

    }
    
    NSDictionary * dic = _goodsArray[indexPath.section][@"mallCartDetail"][indexPath.row];
    cell.goodsName.text = [NSString stringWithFormat:@"%@",dic[@"mallGoods"][@"mgooName"]];
    cell.price.text = [NSString stringWithFormat:@"￥%@",dic[@"mallGoods"][@"mgooPrice"]];
    cell.type.text = [NSString stringWithFormat:@"%@/块",dic[@"mallGoods"][@"mgooSpecify"]];
    NSString * image =  [NSString stringWithFormat:@"%@",dic[@"mallGoods"][@"mgooImage"]];
    if (image.length>0) {
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    
    cell.numberLabel.text = [NSString stringWithFormat:@"%@",dic[@"mcdeCount"]];
    cell.leftCount.text = [NSString stringWithFormat:@"%@块",dic[@"mcdeCount"]];
    cell.rightCount.text = [NSString stringWithFormat:@"共%@块",dic[@"mcdeCount"]];
    cell.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"mcdeCount"] integerValue]*[dic[@"mallGoods"][@"mgooPrice"] floatValue]];
    
    
    cell.choseButton.selected = NO;
    for (int i = 0; i<_choseDic.allValues.count; i++) {
        NSIndexPath * path = _choseDic.allValues[i];
        if (path.section == indexPath.section && path.row == indexPath.row) {
            cell.choseButton.selected = YES;
        }
    }
    
    cell.choseBlock = ^(BOOL chose){
        if (chose == YES) {
            
            [_choseDic setObject:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section] forKey:[NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row] ];
            
        }else{
            [_choseDic removeObjectForKey:[NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row]];
        }
        
        NSInteger count = 0;
        for (int i = 0; i<_choseDic.allKeys.count; i++) {
            NSString * key = _choseDic.allKeys[i];
            if ([[key substringToIndex:1] isEqualToString:[NSString stringWithFormat:@"%ld",(long)indexPath.section]]) {
                count ++;
            }
        }
        NSArray * array = _goodsArray[indexPath.section][@"mallCartDetail"];
        if (array.count == count) {
            UIButton * button = (UIButton *)[self.view viewWithTag:100*(indexPath.section+1)+1] ;
            button.selected = YES;
            UIButton * Button = (UIButton *)[self.view viewWithTag:100*(indexPath.section+1)] ;
            Button.selected = YES;
        }else
        {
            UIButton * button = (UIButton *)[self.view viewWithTag:100*(indexPath.section+1)+1] ;
            button.selected = NO;
            UIButton * Button = (UIButton *)[self.view viewWithTag:100*(indexPath.section+1)] ;
            Button.selected = NO;
        }
        
        [self countPrice];
        
    };
    
    cell.addBlock = ^(){
        NSMutableDictionary * dic = [_goodsArray[indexPath.section][@"mallCartDetail"][indexPath.row] mutableCopy];
        NSInteger number = [dic[@"mcdeCount"] integerValue];
        number += 1;
        [dic setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"mcdeCount"];
        [_goodsArray[indexPath.section][@"mallCartDetail"] replaceObjectAtIndex:indexPath.row withObject:dic];
        
        NSArray * array = _choseDic.allKeys;
        if ([array containsObject:[NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row]]) {
            [self countPrice];
        }
        [_tableView reloadData];
        

        NSMutableDictionary  *dict=[NSMutableDictionary dictionary];
        
        [dict setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dict setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
        [dict setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dict setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        NSString * lan = [InternationalControl userLanguage];
        if ([lan isEqualToString:@"en"]) {
            [dict setObject:@"2" forKey:@"language"];
        }else{
            [dict setObject:@"1" forKey:@"language"];
        }
       [dict setObject:dic[@"mallGoods"][@"mgooId"] forKey:@"mgooId"];
        [dict setObject:@"1" forKey:@"flag"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dict withPath:GS_saveAddCartNum withHttpType:@"POST" withTag:GS_GS_saveAddCartNum];

    };
    
    cell.deleteBlock = ^(){
        NSMutableDictionary * dic = [_goodsArray[indexPath.section][@"mallCartDetail"][indexPath.row] mutableCopy];
        NSInteger number = [dic[@"mcdeCount"] integerValue];
       
        if (number<=1) {//不能减了
            number = 1;
            [[CWHUDTips sharedInstance]  showTips:@"受不了了，不能再减少了哦"];
        }else{//可以继续减
             number -= 1;
            NSMutableDictionary  *dict=[NSMutableDictionary dictionary];
            
            [dict setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
            [dict setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
            [dict setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
            [dict setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
            NSString * lan = [InternationalControl userLanguage];
            if ([lan isEqualToString:@"en"]) {
                [dict setObject:@"2" forKey:@"language"];
            }else{
                [dict setObject:@"1" forKey:@"language"];
            }
            [dict setObject:dic[@"mallGoods"][@"mgooId"] forKey:@"mgooId"];
            [dict setObject:@"2" forKey:@"flag"];
            self.shareApi.delegate=self;
            [self.shareApi  requestOperationWithDic:dict withPath:GS_saveAddCartNum withHttpType:@"POST" withTag:GS_GS_saveAddCartNum];
        }
        [dic setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"mcdeCount"];
        [_goodsArray[indexPath.section][@"mallCartDetail"] replaceObjectAtIndex:indexPath.row withObject:dic];
        
        if (number>0){
            NSArray * array = _choseDic.allKeys;
            if ([array containsObject:[NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row]]) {
                [self countPrice];
                
            }
        }
        
        [_tableView reloadData];
    };

    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
//    UIViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"BusinessInfoDetail"];
//    [[Common getNavigation]pushViewController:page];
//    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==GS_GS_queryCartList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                if([database[@"result"] isEqual:[NSNull null]]){
                    return ;
                }
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.goodsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
            if (![arr isEqual:[NSNull null]]) {
                for (id entity in arr) {
                    [self.goodsArray addObject:entity];
                }
            }
                [_tableView reloadData];
                
            });
        
        }
        
    }else if (tag == GS_GS_saveAddCartNum){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }
    }else if (tag == GS_GS_deleteCartGoods){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            _countView.hidden = NO;
            _ifDelete = NO;
            _deleteButton.selected = NO;
            [_choseDic removeAllObjects];
            [_tableView.header beginRefreshing];
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
